package com.slj.spring_security_demo.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableMethodSecurity
public class WebSecurityConfig {


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 默认请求全部都需要授权
        http.authorizeHttpRequests(authorize -> authorize.requestMatchers(HttpMethod.GET, "/users")
                .hasRole("admin")
                .anyRequest()
                .authenticated());
        // 登录成功和失败返回的数据
        http.formLogin(login -> login.loginPage("/login").permitAll()
                .successHandler(new MyAuthenticationSuccessHandler())
                .failureHandler(new MyAuthenticationFailureHandler()));
        // 登出返回数据
        http.logout(logout -> logout.logoutSuccessHandler(new MyLogoutHandler()));
        // 认证失败返回的数据格式
        http.exceptionHandling(exception -> exception.authenticationEntryPoint(new MyAuthenticationEntryPoint())
                .accessDeniedHandler(new MyAccessDeniedHandler()));
        // 跨域请求
        http.cors(withDefaults());
        http.httpBasic(withDefaults());
        return http.build();
    }

    @Bean
    public DBUserDetailsManager dbUserDetailsManager() {
        return new DBUserDetailsManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}